package jwei.apps.json;

import java.util.ArrayList;
import java.util.List;

import jwei.apps.objects.PurchasedStyle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonToPurchasedStyle {

    public static PurchasedStyle convertToPurchasedStyle(JSONObject s) {
        try {
            String styleId = s.getString("styleId");
            if (styleId == null || styleId.equals("")) { return null; }

            String productId = s.getString("productId");
            if (productId == null || productId.equals("")) { return null; }

            // send in the product id referencing the original item
            PurchasedStyle style = new PurchasedStyle(Long.parseLong(styleId), Long.parseLong(productId));

            if (s.has("brandName")) {
                style.setBrandName(s.getString("brandName"));
            }

            if (s.has("productName")) {
                style.setProductName(s.getString("productName"));
            }

            if (s.has("price")) {
                style.setPrice(s.getString("price"));
            }

            if (s.has("thumbnailImageUrl")) {
                style.setImageUrl(s.getString("thumbnailImageUrl"));
            } else if (s.has("defaultImageUrl")) {
                style.setImageUrl(s.getString("defaultImageUrl"));
            }

            if (s.has("productUrl")) {
                style.setProductUrl(s.getString("productUrl"));
            } else if (s.has("defaultProductUrl")) {
                style.setProductUrl(s.getString("defaultProductUrl"));
            }

            if (s.has("date")) {
                style.setDate(s.getString("date"));
            }

            if (s.has("state")) {
                style.setState(s.getString("state"));
            }

            return style;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<PurchasedStyle> convertToPurchasedStyles(JSONArray jarray) {
        List<PurchasedStyle> results = new ArrayList<PurchasedStyle>();
        try {
            for (int i = 0; i < jarray.length(); i++) {
                JSONObject s = jarray.getJSONObject(i);
                PurchasedStyle sty = convertToPurchasedStyle(s);
                results.add(sty);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return results;
    }

}
